var config = require('./config');
var url = config.dsh.members.url;
var token = config.dsh.token;
var openidUrl = config.dsh.members.openidUrl;

var login = {
  // 获取openid并检查该用户是否在member表里
  check_member : function(){
    // 调用登录接口
      wx.login({
        success: function (e) {
          wx.request({
            url: config.service.loginUrl,
            data: {
              code: e.code,
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
                // console.log('-----获取openid  userinfo-------');
                // console.log(res.data)
                wx.setStorageSync('openid', res.data.openid);
                wx.setStorageSync('userinfo', res.data.userinfo);
              // 连接服务器
              set_member(res.data.openid);
            },
            fail: function (res) {
              console.log(res)
            }
          })
          console.log('wxlogin successd........');
        }
      });

    
  },
  get_member_by_openid : function(openid){

  },
  set_member : function(){

  }
}


var set_member = function(openid) {
  // 先查询该openid有没有
  wx.request({
    url: openidUrl + openid,
    success:function(res){
        console.log(res);
      var data = res.data;
      if(data.length == 0){
        new_member(openid);
      }else{
        wx.setStorageSync('member', data);
      }
    }
  });
}

var new_member = function (openid) {
  console.log('*****我要来新增member啦*******');
  // 获取微信基本信息
  wx.getUserInfo({
    success: function (res) {
      var userInfo = res.userInfo;
      // 然后新增
      wx.request({
        url: url,
        method: 'POST',
        data: {
          openid: openid,
          nickname: userInfo.nickName,
          headimg: userInfo.avatarUrl
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.setStorageSync('member', res.data);
          console.log('*******获取memeber信息成功*******');
        }
      });
    }
  });
}

module.exports = {
  func: login,
};
